package org.cloudfoundry.samples;

import java.util.List;

import javax.inject.Inject;

import org.cloudfoundry.samples.domain.MobileInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

	@Inject
	private ReferenceDataRepository referenceRepository;
	
	/**
	 * Prepares the Model with some metadata and the list of States retrieved
	 * from the DB. Then, selects the home view to render by returning its name.
	 */
	@RequestMapping(value="/", method=RequestMethod.GET)
	public String home(Model model) {
		logger.info("Welcome home!");
		model.addAttribute("dbinfo", referenceRepository.getDbInfo());
		model.addAttribute("states", referenceRepository.findAll());
		return "home";
	}

	/**
     * Retrieve a list of states. Accepts a GET request for JSON
     * @return A JSON array of states
     */
    @RequestMapping(value = "/mobile", method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody List<MobileInfo> fetchStatesJson() {
        logger.info("fetching JSON states");
        return referenceRepository.getMobiles();
    }
    
    /**
     * Accepts a POST request with an Map message parameter, and creates a new Message object from the Map parameters.
     * @param map serialized LinkedMultiValueMap<String, String> object
     * @return a string with the result of the POST
     */
    @RequestMapping(value = "sendmessagemap", method = RequestMethod.POST)
    public @ResponseBody String sendMessageMap(@RequestBody LinkedMultiValueMap<String, String> map) {
    	MobileInfo message = new MobileInfo();

        try {
            message.setId(Long.parseLong(map.getFirst("id")));
        } catch (NumberFormatException e) {
            message.setId(0L);
        }

        message.setMobileNumber(map.getFirst("mobilenumber"));
        message.setDeviceId(map.getFirst("deviceid"));

        logger.info("Map message: " + message.toString());
        
        referenceRepository.saveMobileInfo(message);
        
        return "Map message received! Your message: " + message.toString();
    }
}
